package com.dong.multithreading;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;

import java.io.*;

public class BloomFilterTest2 {
    public static void main(String[] args) throws FileNotFoundException {
        writeFile();
        readFile();
    }

    private static void writeFile() throws FileNotFoundException {
        BloomFilter<Integer> filter = BloomFilter.create(
                Funnels.integerFunnel(),
                500,
                0.01);
        // 导入数据到filter
        for (int i = 0; i < 100; i++) {
            filter.put(i);
        }
        // 数据持久化到本地
        File f = new File("E:" + File.separator + "tmp" + File.separator + "test2");
        OutputStream out = new FileOutputStream(f);
        try {
            filter.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void readFile() throws FileNotFoundException {
        BloomFilter<Integer> filter = BloomFilter.create(
                Funnels.integerFunnel(),
                500,
                0.01);
        // 将之前持久化的数据加载到Filter
        File f = new File("E:" + File.separator + "tmp" + File.separator + "test2");
        try (InputStream in = new FileInputStream(f)){
            filter = BloomFilter.readFrom(in, Funnels.integerFunnel());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 测试验证
        for (int i = 0; i < 110; i++) {
            boolean result = filter.mightContain(i);
            System.out.println("i = " + i + " " + result);
        }
    }
}
